package mamikeji.liaowa.ui.activity.diary;

import android.app.Dialog;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import mamikeji.liaowa.R;
import mamikeji.liaowa.application.MyApplication;
import mamikeji.liaowa.bean.DiaryDayBean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.BaseActivity;
import mamikeji.liaowa.ui.adapter.User_DiaryAdapter;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MultiStateView;
import mamikeji.liaowa.widget.floatingactionbutton.FloatingActionButton;
import mamikeji.liaowa.widget.refreshView.PtrlDownRefreshFrameLayout;

public class UserDiaryActivity extends BaseActivity {
    private static final String TAG = "UserDiaryActivity";
    private ListView listView_user_diary;
    private PtrlDownRefreshFrameLayout ptrlDownRefreshFrameLayout_user_diary;
    private View header_view, foot_view;
    private User_DiaryAdapter user_diaryAdapter;
    private FloatingActionButton multiple_diary_add;
    private TextView header_diary_childitem_time;

    List<DiaryDayBean.DataBean> dataBeanList;
    private MultiStateView multiStateView_user_diary;

    private Dialog dialog_share,dialog_share_query;

    private int positions;
    private int diary_id_s;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_diary);
        getBase();
        setTitleLeftBtn();
        setTitleName(R.string.user_diary_name);

        init();
        initData();
        getDialogShare();
        getDigLog();
        showDeleteDialog();
    }

    /**
     * 加载布局控件
     */
    private void init() {
        multiple_diary_add = (FloatingActionButton) findViewById(R.id.multiple_diary_add);
        ptrlDownRefreshFrameLayout_user_diary = (PtrlDownRefreshFrameLayout) findViewById(R.id.ptrlDownRefreshFrameLayout_user_diary);
        listView_user_diary = (ListView) findViewById(R.id.listView_user_diary);

        header_view = LayoutInflater.from(MyApplication.getContext()).inflate(R.layout.item_user_diary_header, null);
        listView_user_diary.addHeaderView(header_view);

        header_diary_childitem_time = (TextView) header_view.findViewById(R.id.header_diary_childitem_time);

        foot_view = LayoutInflater.from(MyApplication.getContext()).inflate(R.layout.item_user_diary_foot, null);
        listView_user_diary.addFooterView(foot_view);

        dataBeanList = new ArrayList<>();

        user_diaryAdapter = new User_DiaryAdapter(dataBeanList, this);
        listView_user_diary.setAdapter(user_diaryAdapter);

        multiStateView_user_diary = (MultiStateView) findViewById(R.id.multiStateView_user_diary);

        multiStateView_user_diary.getView(MultiStateView.VIEW_STATE_ERROR).findViewById(R.id.button_error_refish)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        multiStateView_user_diary.setViewState(MultiStateView.VIEW_STATE_LOADING);
                        getDayDiary();
                    }
                });

        multiStateView_user_diary.setEmptyText(R.string.user_diary_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(UserDiaryActivity.this, PublishDiaryActivity.class));
                finish();
            }
        });

        StringData();

        ptrlDownRefreshFrameLayout_user_diary.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, listView_user_diary, header);
            }
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getDayDiary();
            }
        });

        user_diaryAdapter.setOnItemClickListener(new User_DiaryAdapter.OnItemClickListener() {
            @Override
            public void onShareClick(int position) {
                if (!user_diaryAdapter.bool_delete){
                    positions = position;
                    dialog_share.show();
                }
            }

            @Override
            public void onDeleteClick(int diary_id, int position) {
                positions = position;
                diary_id_s = diary_id;
                dialog_delete.show();
            }
        });

        multiple_diary_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(UserDiaryActivity.this, PublishDiaryActivity.class));
                finish();
            }
        });
    }

    /**
     * 初始化数据
     */
    private void initData() {
        getDayDiary();
    }

    /**
     * 获取当天随笔
     */
    public void getDayDiary() {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.ESSAY_DAY_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        ForHttp.getMsg(HttpApi.ROOT_PATH + HttpApi.ESSAY_DAY + "?"
                + HttpKey.ESSAY_DAY_USERCODE + "=" + ForPreference.getString(ForContents.USER_CODE), new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                multiStateView_user_diary.setViewState(MultiStateView.VIEW_STATE_NOINTERNET);
                ptrlDownRefreshFrameLayout_user_diary.refreshComplete();
            }

            @Override
            public void onResponse(String response) {
                Log.e(TAG, response);
                ptrlDownRefreshFrameLayout_user_diary.refreshComplete();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        DiaryDayBean diaryDayBean = new Gson().fromJson(response, DiaryDayBean.class);
                        if (diaryDayBean.getData() != null) {
                            if (diaryDayBean.getData().size() > 0) {
                                setTitleRightBtn(R.string.user_diary_delete, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        /**震动服务*/
                                        Vibrator vib = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
                                        vib.vibrate(50);//只震动一秒，一次

                                        user_diaryAdapter.bool_delete = !user_diaryAdapter.bool_delete;
                                        user_diaryAdapter.notifyDataSetChanged();
                                    }
                                });

                                dataBeanList = diaryDayBean.getData();
                                user_diaryAdapter.setList(dataBeanList);
                                multiStateView_user_diary.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                            } else {
                                multiStateView_user_diary.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                            }
                        } else {
                            multiStateView_user_diary.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                        }
                    } else {
                        multiStateView_user_diary.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void publicCircle(String content, String imagePath, String type) {
        showLoading();
        Map<String, String> formMap = new HashMap<>();
        formMap.put("fc_UserId", ForPreference.getString(ForContents.USER_CODE));
        formMap.put("fc_Titile", content);
        formMap.put("fc_Titile", content);
        formMap.put("fc_Content", content);
        formMap.put("fc_ContentType", type);//朋友圈内容类型 1文字 2图片 3图品文字 ,
        formMap.put("fc_ImageUrl", imagePath);
        formMap.put("fc_Type", "1");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.PUBLIC_CIRCLE, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForToast.showToast(R.string.intent_error);
                hideLoading();
                ForPreference.putBoolean(ForContents.DIARY_SHARE_BOOL,false);
            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        ForToast.showToast("分享成功");
                        ForPreference.putBoolean(ForContents.DIARY_SHARE_BOOL,true);
                        finish();
                    } else {
                        ForPreference.putBoolean(ForContents.DIARY_SHARE_BOOL,false);
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                    hideLoading();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        //获取当天随笔
        getDayDiary();
    }

    /**
     * 设置头部当前时间
     */
    private String mMonth, mDay;

    public void StringData() {
        final Calendar c = Calendar.getInstance();
        c.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        mMonth = String.valueOf(c.get(Calendar.MONTH) + 1);// 获取当前月份
        mDay = String.valueOf(c.get(Calendar.DAY_OF_MONTH));// 获取当前月份的日期号码
        header_diary_childitem_time.setText(mMonth + "月" + mDay + "号");
    }

    /**
     * 分享弹框
     */
    public void getDialogShare() {
        dialog_share = new Dialog(this, R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(this).inflate(R.layout.diglog_set_shape, null);
        dialog_share.setContentView(view);
        Window dialogWindow = dialog_share.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 0;
        lp.width = getResources().getDisplayMetrics().widthPixels; // 宽度
        dialogWindow.setAttributes(lp);

        RelativeLayout relativeLayout_share_liaowa = (RelativeLayout) view.findViewById(R.id.relativeLayout_share_liaowa);
        relativeLayout_share_liaowa.setVisibility(View.VISIBLE);
        LinearLayout linearLayout_share_liaowa = (LinearLayout) view.findViewById(R.id.linearLayout_share_liaowa);
        LinearLayout linearLayout_share_wechatFriend = (LinearLayout) view.findViewById(R.id.linearLayout_share_wechatFriend);
        LinearLayout linearLayout_share_wechatCircle = (LinearLayout) view.findViewById(R.id.linearLayout_share_wechatCircle);
        LinearLayout linearLayout_share_tencentCircle = (LinearLayout) view.findViewById(R.id.linearLayout_share_tencentCircle);

        linearLayout_share_liaowa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog_share_query.show();
            }
        });
        linearLayout_share_wechatFriend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog_share.hide();
                ShareWeb(SHARE_MEDIA.WEIXIN);
            }
        });
        linearLayout_share_wechatCircle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog_share.hide();
                ShareWeb(SHARE_MEDIA.WEIXIN_CIRCLE);
            }
        });
        linearLayout_share_tencentCircle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog_share.hide();
                ShareWeb(SHARE_MEDIA.QZONE);
            }
        });
    }

    /**
     * 分享回调
     *
     * @param anEnum
     */
    private void ShareWeb(Enum anEnum) {
        UMImage thumb = new UMImage(this, R.mipmap.ic_launcher);
        UMWeb web = new UMWeb("https://www.baidu.com");
        web.setThumb(thumb);
        web.setDescription("为亿万用户提供个性化的每日育儿指导，不用搜索，不用导航，轻轻一点，每日育儿即可直接呈现");
        web.setTitle("下载撩娃APP，让育儿如此简单！");
        new ShareAction(this).withMedia(web).setPlatform((SHARE_MEDIA) anEnum).setCallback(new UMShareListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
                ForToast.showToast("后台正在玩儿命加载~~~");
            }

            @Override
            public void onResult(SHARE_MEDIA share_media) {
                ForToast.showToast("分享成功！");
            }

            @Override
            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                ForToast.showToast("分享失败！");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {
                ForToast.showToast("取消分享！");
            }
        }).share();
    }

    private TextView textView_dig_cache_text;
    private RelativeLayout relativeLayout_set_dig_btnerror,relativeLayout_set_dig_query;

    private void getDigLog(){
        dialog_share_query = new Dialog(UserDiaryActivity.this, R.style.DialogLoading);
        View inflate = LayoutInflater.from(UserDiaryActivity.this).inflate(R.layout.diglog_set_clearcache, null);
        dialog_share_query.setContentView(inflate);

        textView_dig_cache_text = (TextView) inflate.findViewById(R.id.textView_dig_cache_text);
        relativeLayout_set_dig_btnerror = (RelativeLayout) inflate.findViewById(R.id.relativeLayout_set_dig_btnerror);
        relativeLayout_set_dig_query = (RelativeLayout) inflate.findViewById(R.id.relativeLayout_set_dig_query);

        textView_dig_cache_text.setText("是否分享到妈蜜圈？");

        relativeLayout_set_dig_btnerror.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog_share_query.hide();
            }
        });
        relativeLayout_set_dig_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (dataBeanList.get(positions).getImages().size() > 0) {
                    StringBuffer imagePath = new StringBuffer();
                    for (int i = 0; i < dataBeanList.get(positions).getImages().size(); i++) {
                        if (i == dataBeanList.get(positions).getImages().size() - 1) {
                            imagePath.append(dataBeanList.get(positions).getImages().get(i));
                        } else {
                            imagePath.append(dataBeanList.get(positions).getImages().get(i) + ",");
                        }
                    }
                    if (dataBeanList.get(positions).getContent().equals("") || dataBeanList.get(positions).getContent() == null){
                        publicCircle("", imagePath.toString() , "2");
                    }else {
                        publicCircle(dataBeanList.get(positions).getContent(), imagePath.toString() , "3");
                    }
                } else {
                    publicCircle(dataBeanList.get(positions).getContent(), "" , "1");
                }
            }
        });
    }

    /**
     * 确认删除
     */
    private Dialog dialog_delete;
    private RelativeLayout relativeLayout_clock_dig_query, relativeLayout_clock_dig_btnerror;
    private void showDeleteDialog() {
        dialog_delete = new Dialog(UserDiaryActivity.this, R.style.DialogLoading);
        View inflate = LayoutInflater.from(UserDiaryActivity.this).inflate(R.layout.diglog_clock_delete, null);
        dialog_delete.setContentView(inflate);

        relativeLayout_clock_dig_query = (RelativeLayout) inflate.findViewById(R.id.relativeLayout_clock_dig_query);
        relativeLayout_clock_dig_btnerror = (RelativeLayout) inflate.findViewById(R.id.relativeLayout_clock_dig_btnerror);

        relativeLayout_clock_dig_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog_delete.hide();

                getDelete_DiaryData();
            }
        });
        relativeLayout_clock_dig_btnerror.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog_delete.hide();
            }
        });
    }

    private void getDelete_DiaryData() {
        showLoading();
        //参数集合
        Map<String, String> formMap = new HashMap<>();
//        formMap.put(HttpKey.ESSAY_DELETE_ID, diary_id_s+"");
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.ESSAY_DELETE_DATE
                + "?" + HttpKey.ESSAY_DELETE_ID + "=" + diary_id_s, formMap , new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                hideLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        ForToast.showToast("已删除！");

                        dataBeanList.remove(positions);
                        user_diaryAdapter.notifyDataSetChanged();

                        if (dataBeanList.size() <= 0){
                            multiStateView_user_diary.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                        }
                    } else {
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}